﻿using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;

namespace MvcApplication1.Models
{
    public sealed class CustomMembershipProvider : MembershipProvider
        {

            public CustomMembershipProvider()
            {

            }
            //----------------unit test--------------------------------------
            public CustomMembershipProvider(string connstr)
            {
                connectionString = connstr;
            }
            //----------------unit test--------------------------------------

            //
            // Global connection string, generated password length, generic exception message, event log info.
            //

            //private int newPasswordLength = 8;
            private string eventSource = "CustomMembershipProvider";
            private string eventLog = "Application";
            private string exceptionMessage = "An exception occurred. Please check the Event Log.";
            private string connectionString;

            //
            // Used when determining encryption key values.
            //

            private MachineKeySection machineKey;

            //
            // If false, exceptions are thrown to the caller. If true,
            // exceptions are written to the event log.
            //

            private bool pWriteExceptionsToEventLog;

            public bool WriteExceptionsToEventLog
            {
                get { return pWriteExceptionsToEventLog; }
                set { pWriteExceptionsToEventLog = value; }
            }


            //
            // System.Configuration.Provider.ProviderBase.Initialize Method
            //

            public override void Initialize(string name, NameValueCollection config)
            {
                //
                // Initialize values from web.config.
                //

                if (config == null)
                    throw new ArgumentNullException("config");

                if (name == null || name.Length == 0)
                    name = "CustomMembershipProvider";

                if (String.IsNullOrEmpty(config["description"]))
                {
                    config.Remove("description");
                    config.Add("description", "Custom Membership provider");
                }

                // Initialize the abstract base class.
                base.Initialize(name, config);

                pApplicationName = GetConfigValue(config["applicationName"],
                                                System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                pMaxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
                pPasswordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
                pMinRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonAlphanumericCharacters"], "1"));
                pMinRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7"));
                pPasswordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
                pEnablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "false"));
                pEnablePasswordRetrieval = Convert.ToBoolean(GetConfigValue(config["enablePasswordRetrieval"], "true"));
                pRequiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "false"));
                pRequiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "false"));
                pWriteExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "false"));

                string temp_format = config["passwordFormat"];
                if (temp_format == null)
                {
                    temp_format = "Hashed";
                }

                switch (temp_format)
                {
                    case "Hashed":
                        pPasswordFormat = MembershipPasswordFormat.Hashed;
                        break;
                    case "Encrypted":
                        pPasswordFormat = MembershipPasswordFormat.Encrypted;
                        break;
                    case "Clear":
                        pPasswordFormat = MembershipPasswordFormat.Clear;
                        break;
                    default:
                        throw new ProviderException("Password format not supported.");
                }

                //
                // Initialize DBConnection.
                //

                ConnectionStringSettings ConnectionStringSettings =
                  ConfigurationManager.ConnectionStrings["cj"];

                if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "")
                {
                    throw new ProviderException("Connection string cannot be blank.");
                }

                connectionString = ConnectionStringSettings.ConnectionString;


                // Get encryption and decryption key information from the configuration.
                Configuration cfg =
                  WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");

                if (machineKey.ValidationKey.Contains("AutoGenerate"))
                    if (PasswordFormat != MembershipPasswordFormat.Clear)
                        throw new ProviderException("Hashed or Encrypted passwords " +
                                                    "are not supported with auto-generated keys.");
            }


            //
            // A helper function to retrieve config values from the configuration file.
            //

            private string GetConfigValue(string configValue, string defaultValue)
            {
                if (String.IsNullOrEmpty(configValue))
                    return defaultValue;

                return configValue;
            }


            //
            // System.Web.Security.MembershipProvider properties.
            //


            private string pApplicationName;
            private bool pEnablePasswordReset;
            private bool pEnablePasswordRetrieval;
            private bool pRequiresQuestionAndAnswer;
            private bool pRequiresUniqueEmail;
            private int pMaxInvalidPasswordAttempts;
            private int pPasswordAttemptWindow;
            private MembershipPasswordFormat pPasswordFormat;

            public override string ApplicationName
            {
                get { return pApplicationName; }
                set { pApplicationName = value; }
            }

            public override bool EnablePasswordReset
            {
                get { return pEnablePasswordReset; }
            }


            public override bool EnablePasswordRetrieval
            {
                get { return pEnablePasswordRetrieval; }
            }


            public override bool RequiresQuestionAndAnswer
            {
                get { return pRequiresQuestionAndAnswer; }
            }


            public override bool RequiresUniqueEmail
            {
                get { return pRequiresUniqueEmail; }
            }


            public override int MaxInvalidPasswordAttempts
            {
                get { return pMaxInvalidPasswordAttempts; }
            }


            public override int PasswordAttemptWindow
            {
                get { return pPasswordAttemptWindow; }
            }


            public override MembershipPasswordFormat PasswordFormat
            {
                get { return pPasswordFormat; }
            }

            private int pMinRequiredNonAlphanumericCharacters;

            public override int MinRequiredNonAlphanumericCharacters
            {
                get { return pMinRequiredNonAlphanumericCharacters; }
            }

            private int pMinRequiredPasswordLength;

            public override int MinRequiredPasswordLength
            {
                get { return pMinRequiredPasswordLength; }
            }

            private string pPasswordStrengthRegularExpression;

            public override string PasswordStrengthRegularExpression
            {
                get { return pPasswordStrengthRegularExpression; }
            }

            //
            // System.Web.Security.MembershipProvider methods.
            //

            //
            // MembershipProvider.ChangePassword
            //

            public override bool ChangePassword(string username, string oldPwd, string newPwd)
            {
                if (!ValidateUser(username, oldPwd))
                    return false;


                ValidatePasswordEventArgs args =
                  new ValidatePasswordEventArgs(username, newPwd, true);

                OnValidatingPassword(args);

                if (args.Cancel)
                    if (args.FailureInformation != null)
                        throw args.FailureInformation;
                    else
                        throw new MembershipPasswordException("Change password canceled due to new password validation failure.");


                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("UPDATE [dbo].[user] " +
                        " SET password = @password" +
                        " WHERE username = @username", conn);

                cmd.Parameters.Add("@password", SqlDbType.NVarChar,100).Value = EncodePassword(newPwd);
                cmd.Parameters.Add("@username", SqlDbType.NVarChar,50).Value = username;


                int rowsAffected = 0;

                try
                {
                    conn.Open();

                    rowsAffected = cmd.ExecuteNonQuery();
                }
                catch (SqlException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "ChangePassword");

                        throw new ProviderException(exceptionMessage);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                    conn.Close();
                }

                if (rowsAffected > 0)
                {
                    return true;
                }

                return false;
            }



            //
            // MembershipProvider.ChangePasswordQuestionAndAnswer
            //

            public override bool ChangePasswordQuestionAndAnswer(string username,
                          string password,
                          string newPwdQuestion,
                          string newPwdAnswer)
            {
                throw new NotSupportedException("this function is not enabled.");
                //if (!ValidateUser(username, password))
                //    return false;

                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
                //        " SET PasswordQuestion = ?, PasswordAnswer = ?" +
                //        " WHERE Username = ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@Question", OdbcType.VarChar, 255).Value = newPwdQuestion;
                //cmd.Parameters.Add("@Answer", OdbcType.VarChar, 255).Value = EncodePassword(newPwdAnswer);
                //cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;


                //int rowsAffected = 0;

                //try
                //{
                //    conn.Open();

                //    rowsAffected = cmd.ExecuteNonQuery();
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "ChangePasswordQuestionAndAnswer");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    conn.Close();
                //}

                //if (rowsAffected > 0)
                //{
                //    return true;
                //}

                //return false;
            }



            //
            // MembershipProvider.CreateUser
            //
            public override MembershipUser CreateUser(string username,
                     string password,
                     string email,
                     string passwordQuestion,
                     string passwordAnswer,
                     bool isApproved,
                     Object providerUserKey,
                     out MembershipCreateStatus status)
            {
                ValidatePasswordEventArgs args =
                  new ValidatePasswordEventArgs(username, password, true);

                OnValidatingPassword(args);

                if (args.Cancel)
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return null;
                }


                MembershipUser u = GetUser(username,false);

                if (u == null)
                {
                    DateTime createDate = DateTime.Now;

                    SqlConnection conn = new SqlConnection(connectionString);
                    SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[user] " +
                          " (username, password, email," +
                          " isapproved," +
                          " creationdate," +
                          " lastlogin)" +
                          " Values(@username, @password, @email, @isapproved, @creationdate, @lastlogin)", conn);

                    
                    cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
                    cmd.Parameters.Add("@password", SqlDbType.NVarChar, 100).Value = EncodePassword(password);
                    cmd.Parameters.Add("@email", SqlDbType.Text, 128).Value = DBNull.Value;
                    cmd.Parameters.Add("@isapproved", SqlDbType.Bit).Value = isApproved;
                    cmd.Parameters.Add("@creationdate", SqlDbType.DateTime).Value = createDate;
                    cmd.Parameters.Add("@lastlogin", SqlDbType.DateTime).Value = createDate;
                   
                    try
                    {
                        conn.Open();

                        int recAdded = cmd.ExecuteNonQuery();

                        if (recAdded > 0)
                        {
                            status = MembershipCreateStatus.Success;
                        }
                        else
                        {
                            status = MembershipCreateStatus.UserRejected;
                        }
                    }
                    catch (SqlException e)
                    {
                        if (WriteExceptionsToEventLog)
                        {
                            WriteToEventLog(e, "CreateUser");
                        }

                        status = MembershipCreateStatus.ProviderError;
                    }
                    finally
                    {
                        conn.Close();
                    }


                    return GetUser(username,false);
                }
                else
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                }


                return null;
            }

            //
            //create the brand
            //
            public MembershipBrand CreateBrand(string brandname, string linkaddr,Int64 userid)
            {
                MembershipBrand newbrand;
                if (!string.IsNullOrWhiteSpace(brandname))
                {
                    
                    newbrand = new MembershipBrand(brandname, linkaddr, "", userid, DateTime.Now, "", 0,"",""); 
                
                    SqlConnection conn = new SqlConnection(connectionString);
                    SqlCommand cmd = new SqlCommand("INSERT INTO brand ([brandname],[brandIntro],[userID],[registerTime],[linkAddr],[logo],[itemCount],[brandTitle]) VALUES(@brandname,@brandIntro,@userID,@registerTime,@linkAddr,@logo,@itemCount,@brandTitle)", conn);
                    cmd.Parameters.Add("@brandname", SqlDbType.NVarChar, 50).Value = brandname;
                    cmd.Parameters.Add("@brandIntro", SqlDbType.NVarChar).Value = "";
                    cmd.Parameters.Add("@userID", SqlDbType.BigInt).Value = userid;
                    cmd.Parameters.Add("@registerTime", SqlDbType.DateTime).Value = newbrand.RegisterTime;
                    cmd.Parameters.Add("@linkAddr", SqlDbType.NVarChar).Value = linkaddr;
                    cmd.Parameters.Add("@logo", SqlDbType.NVarChar).Value = "";
                    cmd.Parameters.Add("@itemCount", SqlDbType.BigInt).Value = 0;
                    cmd.Parameters.Add("@brandTitle", SqlDbType.NVarChar).Value = "";
                    try
                    {
                        conn.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException e)
                    {
                        throw e;
                    }
                    finally
                    {
                        conn.Close();
                    }
                    return newbrand;
                }
                return null;

            }

            //check whether the brand could be registered
            public bool ValidateBrand(string brandurl,out bool isexisted)
            {
                bool result=false;
                try
                {
                    isexisted = false;
                    //string phypath = HttpContext.Current.Server.MapPath("/52l9/Models/_siteregister.txt");
                    string phypath = HttpContext.Current.Server.MapPath("/Models/_siteregister.txt");
                    using (StreamReader sr = new StreamReader(phypath))
                    {
                        String line;
                        // Read and display lines from the file until the end of
                        // the file is reached.
                        while ((line = sr.ReadLine()) != null)
                        {
                            if(line==brandurl) result=true;
                        }
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("SELECT linkAddr FROM brand WHERE linkAddr=@linkAddr", conn);
                cmd.Parameters.Add("@linkAddr", SqlDbType.NVarChar).Value = brandurl;
                try
                {
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        isexisted=true;
                    }
                    else
                    {
                        isexisted=false;
                    }
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
                return result;
            }
            
            //change the owner of brand to the new user
            public bool ChangeBrandOwner(string brandurl, Int64 userid,string brandname)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("UPDATE brand SET userID=@userid,brandname=@brandname WHERE linkAddr=@linkAddr", conn);
                cmd.Parameters.Add("@userid", SqlDbType.BigInt).Value = userid;
                cmd.Parameters.Add("@brandname", SqlDbType.NVarChar).Value = brandname;
                cmd.Parameters.Add("@linkAddr", SqlDbType.NVarChar).Value = brandurl;
                int rowsAffected = 0;
                try
                {
                    conn.Open();
                    rowsAffected=cmd.ExecuteNonQuery();
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
                if (rowsAffected > 0)
                    return true;

                return false;
            }

            //get the membershipbrand object from the user name
            public MembershipBrand GetBrandFromUserName(string username)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                //SqlConnection conn = new SqlConnection(@"Data Source=ADF4430A0F96498\SQL2008;Initial Catalog=cj;Integrated Security=True"); 单元测试
                SqlCommand cmd = new SqlCommand("SELECT [brandname],[linkAddr],[brandIntro],[userID],[registerTime],[logo],[itemCount],[brandTitle]" +
                                               "FROM [brand] AS b INNER JOIN [user] AS u ON b.userID=u.ID WHERE [username]=@username",conn);
                cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = username;
                MembershipBrand brand=null;
                string keywords = "";
                try
                {
                    conn.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        dr.Read();
                        brand = new MembershipBrand(dr.GetString(0), dr.GetString(1), dr.GetString(2), dr.GetInt64(3), dr.GetDateTime(4), dr.GetString(5), dr.GetInt64(6),dr.GetString(7),"");
                    }
                    dr.Close();
                    cmd.CommandText = "select [keyword] from [brandKeyword] as a inner join [brand] as b on b.ID=a.brandID inner join [user] as c on c.ID=b.userID where c.username=@username order by [keywordSN]";
                    dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        keywords = keywords + dr.GetString(0) + " ";
                    }
                    brand.BrandKeywords = keywords.Trim();
                    dr.Close();
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
                return brand;
            }
            public MembershipBrand GetBrandFromID(Int64 brandID)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("select [brandname],[linkAddr],[brandIntro],[userID],[registerTime],[logo],[itemCount],[brandTitle]" +
                                              "from [brand] where [ID]=@brandID", conn);
                cmd.Parameters.Add("@brandID", SqlDbType.BigInt).Value = brandID;
                MembershipBrand brand = null;
                string keywords="";
                try
                {
                    conn.Open();
                    SqlDataReader dr=cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        dr.Read();
                        brand = new MembershipBrand(dr.GetString(0), dr.GetString(1), dr.GetString(2), dr.GetInt64(3), dr.GetDateTime(4), dr.GetString(5), dr.GetInt64(6),dr.GetString(7),"");
                    }
                    dr.Close();
                    cmd.CommandText="select [keyword] from [brandKeyword] where [brandID]=@brandID order by [keywordSN]";
                    dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        keywords =keywords + dr.GetString(0)+" ";
                    }
                    brand.BrandKeywords = keywords.Trim();
                    dr.Close();
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
                return brand;
            }
            public void UpdateBrandInfo(MembershipBrand brand)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("update [brand] set [brandIntro]=@brandintro,[logo]=@logo,[linkAddr]=@linkaddr,[brandTitle]=@brandtitle where [brandname]=@brandname", conn);
                cmd.Parameters.Add("@brandname", SqlDbType.NVarChar).Value = brand.brandName;
                cmd.Parameters.Add("@brandintro", SqlDbType.NVarChar).Value = brand.brandIntro;
                cmd.Parameters.Add("@logo", SqlDbType.NVarChar).Value = brand.Logo;
                cmd.Parameters.Add("@linkaddr", SqlDbType.NVarChar).Value = brand.linkAddr;
                cmd.Parameters.Add("@brandtitle", SqlDbType.NVarChar).Value = brand.BrandTitle;

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "DELETE a FROM [brandKeyword] as a inner join [brand] as b on a.[brandID]=b.[ID] WHERE b.brandname=@brandname";
                    cmd.ExecuteNonQuery();
                    if (string.IsNullOrEmpty(brand.BrandKeywords) == false)
                    {
                        cmd.CommandText="select [ID] from [brand] where [brandname]=@brandname";
                        Int64 brandid=(long)cmd.ExecuteScalar();
                        cmd.Parameters.Add("@brandid",SqlDbType.BigInt).Value=brandid;
                        cmd.Parameters.Add("@keywordSN",SqlDbType.TinyInt);
                        cmd.Parameters.Add("@keyword",SqlDbType.NVarChar);
                    
                        string[] keywords = brand.BrandKeywords.Split(' ');
                        int sn = 1;
                        foreach (string keyword in keywords)
                        {
                            cmd.CommandText = "insert into [brandKeyword] ([brandID],[keywordSN],[keyword]) values(@brandid,@keywordSN,@keyword)";
                            cmd.Parameters["@keywordSN"].Value = sn;
                            cmd.Parameters["@keyword"].Value = keyword;
                            cmd.ExecuteNonQuery();
                            sn++;
                        }
                    }
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
            }

            //
            // MembershipProvider.DeleteUser
            //

            public override bool DeleteUser(string username, bool deleteAllRelatedData)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("DELETE FROM [dbo].[user] " +
                        " WHERE username = @username", conn);

                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
                
                int rowsAffected = 0;

                try
                {
                    conn.Open();

                    rowsAffected = cmd.ExecuteNonQuery();

                    if (deleteAllRelatedData)
                    {
                        // Process commands to delete all data for the user in the database.
                    }
                }
                catch (SqlException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "DeleteUser");

                        throw new ProviderException(exceptionMessage);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                    conn.Close();
                }

                if (rowsAffected > 0)
                    return true;

                return false;
            }



            //
            // MembershipProvider.GetAllUsers
            //

            public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotSupportedException("this function is not enabled.");
                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                //                                  "WHERE ApplicationName = ?", conn);
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

                //MembershipUserCollection users = new MembershipUserCollection();

                //OdbcDataReader reader = null;
                //totalRecords = 0;

                //try
                //{
                //    conn.Open();
                //    totalRecords = (int)cmd.ExecuteScalar();

                //    if (totalRecords <= 0) { return users; }

                //    cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," +
                //             " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                //             " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " +
                //             " FROM Users " +
                //             " WHERE ApplicationName = ? " +
                //             " ORDER BY Username Asc";

                //    reader = cmd.ExecuteReader();

                //    int counter = 0;
                //    int startIndex = pageSize * pageIndex;
                //    int endIndex = startIndex + pageSize - 1;

                //    while (reader.Read())
                //    {
                //        if (counter >= startIndex)
                //        {
                //            MembershipUser u = GetUserFromReader(reader);
                //            users.Add(u);
                //        }

                //        if (counter >= endIndex) { cmd.Cancel(); }

                //        counter++;
                //    }
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "GetAllUsers ");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }
                //    conn.Close();
                //}

                //return users;
            }


            //
            // MembershipProvider.GetNumberOfUsersOnline
            //

            public override int GetNumberOfUsersOnline()
            {
                throw new NotSupportedException("this function is not enabled.");
                //TimeSpan onlineSpan = new TimeSpan(0, System.Web.Security.Membership.UserIsOnlineTimeWindow, 0);
                //DateTime compareTime = DateTime.Now.Subtract(onlineSpan);

                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                //        " WHERE LastActivityDate > ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@CompareDate", OdbcType.DateTime).Value = compareTime;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //int numOnline = 0;

                //try
                //{
                //    conn.Open();

                //    numOnline = (int)cmd.ExecuteScalar();
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "GetNumberOfUsersOnline");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    conn.Close();
                //}

                //return numOnline;
            }



            //
            // MembershipProvider.GetPassword
            //

            public override string GetPassword(string username, string answer)
            {
                throw new NotSupportedException("this function is not enabled.");
                //if (!EnablePasswordRetrieval)
                //{
                //    throw new ProviderException("Password Retrieval Not Enabled.");
                //}

                //if (PasswordFormat == MembershipPasswordFormat.Hashed)
                //{
                //    throw new ProviderException("Cannot retrieve Hashed passwords.");
                //}

                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT Password, PasswordAnswer, IsLockedOut FROM Users " +
                //      " WHERE Username = ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //string password = "";
                //string passwordAnswer = "";
                //OdbcDataReader reader = null;

                //try
                //{
                //    conn.Open();

                //    reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                //    if (reader.HasRows)
                //    {
                //        reader.Read();

                //        if (reader.GetBoolean(2))
                //            throw new MembershipPasswordException("The supplied user is locked out.");

                //        password = reader.GetString(0);
                //        passwordAnswer = reader.GetString(1);
                //    }
                //    else
                //    {
                //        throw new MembershipPasswordException("The supplied user name is not found.");
                //    }
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "GetPassword");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }
                //    conn.Close();
                //}


                //if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
                //{
                //    UpdateFailureCount(username, "passwordAnswer");

                //    throw new MembershipPasswordException("Incorrect password answer.");
                //}


                //if (PasswordFormat == MembershipPasswordFormat.Encrypted)
                //{
                //    password = UnEncodePassword(password);
                //}

                //return password;
            }



            //
            // MembershipProvider.GetUser(string)
            // 

            public override MembershipUser GetUser(string username, bool userIsOnline)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("SELECT username, email," +
                     " isapproved,creationdate, lastlogin" +
                     " FROM [user] WHERE username = @username", conn);   //注意要用完全限定名指定user表

                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;

                MembershipUser u = null;
                SqlDataReader reader = null;

                try
                {
                    conn.Open();

                    reader = cmd.ExecuteReader();

                    if (reader.HasRows)
                    {
                        reader.Read();
                        u = GetUserFromReader(reader);

                    }

                }
                catch (SqlException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "GetUser(String, Boolean)");

                        throw new ProviderException(exceptionMessage);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                    if (reader != null) { reader.Close(); }

                    conn.Close();
                }

                return u;
            }


            //
            // MembershipProvider.GetUser(object, bool)
            //

            public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
            {
                throw new NotSupportedException("this function is not enabled.");
                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," +
                //      " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                //      " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate" +
                //      " FROM Users WHERE PKID = ?", conn);

                //cmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey;

                //MembershipUser u = null;
                //OdbcDataReader reader = null;

                //try
                //{
                //    conn.Open();

                //    reader = cmd.ExecuteReader();

                //    if (reader.HasRows)
                //    {
                //        reader.Read();
                //        u = GetUserFromReader(reader);

                //        if (userIsOnline)
                //        {
                //            OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " +
                //                      "SET LastActivityDate = ? " +
                //                      "WHERE PKID = ?", conn);

                //            updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now;
                //            updateCmd.Parameters.Add("@PKID", OdbcType.UniqueIdentifier).Value = providerUserKey;

                //            updateCmd.ExecuteNonQuery();
                //        }
                //    }

                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "GetUser(Object, Boolean)");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }

                //    conn.Close();
                //}

                //return u;
            }


            //get user's ID
            public Int64 GetUserID(string username)
            {
                Int64 userid=0;
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("SELECT ID FROM [dbo].[user] WHERE username=@username", conn);
                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
                try
                {
                    conn.Open();
                    userid = (Int64)cmd.ExecuteScalar();
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
                return userid;
            }


            //
            // GetUserFromReader
            //    A helper function that takes the current row from the SqlDataReader
            // and hydrates a MembershiUser from the values. Called by the 
            // MembershipUser.GetUser implementation.
            //

            private MembershipUser GetUserFromReader(SqlDataReader reader)
            {
                //object providerUserKey = reader.GetValue(0);
                string username = reader.GetString(0);

                string email = reader.IsDBNull(1)?null:reader.GetString(1);


                bool isApproved = reader.GetBoolean(2);
                DateTime creationDate = reader.GetDateTime(3);

                DateTime lastLoginDate = new DateTime();
                lastLoginDate = reader.GetDateTime(4);


                MembershipUser u = new MembershipUser(this.Name,
                                                      username,
                                                      null,
                                                      email,
                                                      null,
                                                      null,
                                                      isApproved,
                                                      false,
                                                      creationDate,
                                                      lastLoginDate,
                                                      DateTime.Now,
                                                      DateTime.Now,
                                                      DateTime.Now);

                return u;
            }


            //
            // MembershipProvider.UnlockUser
            //

            public override bool UnlockUser(string username)
            {
                throw new NotSupportedException("this function is not enabled.");
                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("UPDATE Users " +
                //                                  " SET IsLockedOut = False, LastLockedOutDate = ? " +
                //                                  " WHERE Username = ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now;
                //cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //int rowsAffected = 0;

                //try
                //{
                //    conn.Open();

                //    rowsAffected = cmd.ExecuteNonQuery();
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "UnlockUser");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    conn.Close();
                //}

                //if (rowsAffected > 0)
                //    return true;

                //return false;
            }

            public string GetUserNameByLinkUrl(string linkurl)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("SELECT [brandname] FROM brand WHERE linkAddr=@linkAddr", conn);
                cmd.Parameters.Add("@linkAddr", SqlDbType.NVarChar).Value = linkurl;
                string brandname = "";
                try
                {
                    conn.Open();
                    brandname = (string)cmd.ExecuteScalar();
                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    conn.Close();
                }
                return brandname;//当前brandname就是username
            }
            
            //
            // MembershipProvider.GetUserNameByEmail
            //

            public override string GetUserNameByEmail(string email)
            {
                throw new NotSupportedException("this function is not enabled.");
                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT Username" +
                //      " FROM Users WHERE Email = ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@Email", OdbcType.VarChar, 128).Value = email;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //string username = "";

                //try
                //{
                //    conn.Open();

                //    username = (string)cmd.ExecuteScalar();
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "GetUserNameByEmail");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    conn.Close();
                //}

                //if (username == null)
                //    username = "";

                //return username;
            }




            //
            // MembershipProvider.ResetPassword
            //

            public override string ResetPassword(string username, string answer)
            {
                throw new NotSupportedException("Password reset is not enabled.");
                //if (!EnablePasswordReset)
                //{
                //    throw new NotSupportedException("Password reset is not enabled.");
                //}

                //if (answer == null && RequiresQuestionAndAnswer)
                //{
                //    UpdateFailureCount(username, "passwordAnswer");

                //    throw new ProviderException("Password answer required for password reset.");
                //}

                //string newPassword =
                //  System.Web.Security.Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters);


                //ValidatePasswordEventArgs args =
                //  new ValidatePasswordEventArgs(username, newPassword, true);

                //OnValidatingPassword(args);

                //if (args.Cancel)
                //    if (args.FailureInformation != null)
                //        throw args.FailureInformation;
                //    else
                //        throw new MembershipPasswordException("Reset password canceled due to password validation failure.");


                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT PasswordAnswer, IsLockedOut FROM Users " +
                //      " WHERE Username = ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //int rowsAffected = 0;
                //string passwordAnswer = "";
                //OdbcDataReader reader = null;

                //try
                //{
                //    conn.Open();

                //    reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                //    if (reader.HasRows)
                //    {
                //        reader.Read();

                //        if (reader.GetBoolean(1))
                //            throw new MembershipPasswordException("The supplied user is locked out.");

                //        passwordAnswer = reader.GetString(0);
                //    }
                //    else
                //    {
                //        throw new MembershipPasswordException("The supplied user name is not found.");
                //    }

                //    if (RequiresQuestionAndAnswer && !CheckPassword(answer, passwordAnswer))
                //    {
                //        UpdateFailureCount(username, "passwordAnswer");

                //        throw new MembershipPasswordException("Incorrect password answer.");
                //    }

                //    OdbcCommand updateCmd = new OdbcCommand("UPDATE Users " +
                //        " SET Password = ?, LastPasswordChangedDate = ?" +
                //        " WHERE Username = ? AND ApplicationName = ? AND IsLockedOut = False", conn);

                //    updateCmd.Parameters.Add("@Password", OdbcType.VarChar, 255).Value = EncodePassword(newPassword);
                //    updateCmd.Parameters.Add("@LastPasswordChangedDate", OdbcType.DateTime).Value = DateTime.Now;
                //    updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //    updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //    rowsAffected = updateCmd.ExecuteNonQuery();
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "ResetPassword");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }
                //    conn.Close();
                //}

                //if (rowsAffected > 0)
                //{
                //    return newPassword;
                //}
                //else
                //{
                //    throw new MembershipPasswordException("User not found, or user is locked out. Password not Reset.");
                //}
            }


            //
            // MembershipProvider.UpdateUser
            //

            public override void UpdateUser(MembershipUser user)
            {
                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("UPDATE [dbo].[user] " +
                        " SET email = @email," +
                        " isapproved = @isapproved" +
                        " WHERE username = @username", conn);

                cmd.Parameters.Add("@email", SqlDbType.Text, 128).Value = user.Email;
                cmd.Parameters.Add("@isapproved", SqlDbType.Bit).Value = user.IsApproved;
                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = user.UserName;

                try
                {
                    conn.Open();

                    cmd.ExecuteNonQuery();
                }
                catch (SqlException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "UpdateUser");

                        throw new ProviderException(exceptionMessage);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                    conn.Close();
                }
            }


            //
            // MembershipProvider.ValidateUser
            //

            public override bool ValidateUser(string username, string password)
            {
                bool isValid = false;

                SqlConnection conn = new SqlConnection(connectionString);
                SqlCommand cmd = new SqlCommand("SELECT password, isapproved FROM [dbo].[user] " +
                        " WHERE username = @username", conn);

                cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
                
                SqlDataReader reader = null;
                bool isApproved = false;
                string pwd = "";

                try
                {
                    conn.Open();

                    reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                    if (reader.HasRows)
                    {
                        reader.Read();
                        pwd = reader.GetString(0);
                        isApproved = reader.GetBoolean(1);
                    }
                    else
                    {
                        return false;
                    }

                    reader.Close();

                    if (CheckPassword(password, pwd))
                    {
                        if (isApproved)
                        {
                            isValid = true;

                            SqlCommand updateCmd = new SqlCommand("UPDATE [dbo].[user] SET lastlogin = @lastlogin" +
                                                                    " WHERE username = @username", conn);

                            updateCmd.Parameters.Add("@lastlogin", SqlDbType.DateTime).Value = DateTime.Now;
                            updateCmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
                            updateCmd.ExecuteNonQuery();
                        }
                    }
                    else
                    {
                        conn.Close();

                        //UpdateFailureCount(username, "password");
                    }
                }
                catch (SqlException e)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(e, "ValidateUser");

                        throw new ProviderException(exceptionMessage);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                    if (reader != null) { reader.Close(); }
                    conn.Close();
                }

                return isValid;
            }


            //
            // UpdateFailureCount
            //   A helper method that performs the checks and updates associated with
            // password failure tracking.
            //

            private void UpdateFailureCount(string username, string failureType)
            {
                throw new Exception("this function is not enabled");
                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT FailedPasswordAttemptCount, " +
                //                                  "  FailedPasswordAttemptWindowStart, " +
                //                                  "  FailedPasswordAnswerAttemptCount, " +
                //                                  "  FailedPasswordAnswerAttemptWindowStart " +
                //                                  "  FROM Users " +
                //                                  "  WHERE Username = ? AND ApplicationName = ?", conn);

                //cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //OdbcDataReader reader = null;
                //DateTime windowStart = new DateTime();
                //int failureCount = 0;

                //try
                //{
                //    conn.Open();

                //    reader = cmd.ExecuteReader(CommandBehavior.SingleRow);

                //    if (reader.HasRows)
                //    {
                //        reader.Read();

                //        if (failureType == "password")
                //        {
                //            failureCount = reader.GetInt32(0);
                //            windowStart = reader.GetDateTime(1);
                //        }

                //        if (failureType == "passwordAnswer")
                //        {
                //            failureCount = reader.GetInt32(2);
                //            windowStart = reader.GetDateTime(3);
                //        }
                //    }

                //    reader.Close();

                //    DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);

                //    if (failureCount == 0 || DateTime.Now > windowEnd)
                //    {
                //        // First password failure or outside of PasswordAttemptWindow. 
                //        // Start a new password failure count from 1 and a new window starting now.

                //        if (failureType == "password")
                //            cmd.CommandText = "UPDATE Users " +
                //                              "  SET FailedPasswordAttemptCount = ?, " +
                //                              "      FailedPasswordAttemptWindowStart = ? " +
                //                              "  WHERE Username = ? AND ApplicationName = ?";

                //        if (failureType == "passwordAnswer")
                //            cmd.CommandText = "UPDATE Users " +
                //                              "  SET FailedPasswordAnswerAttemptCount = ?, " +
                //                              "      FailedPasswordAnswerAttemptWindowStart = ? " +
                //                              "  WHERE Username = ? AND ApplicationName = ?";

                //        cmd.Parameters.Clear();

                //        cmd.Parameters.Add("@Count", OdbcType.Int).Value = 1;
                //        cmd.Parameters.Add("@WindowStart", OdbcType.DateTime).Value = DateTime.Now;
                //        cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //        cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //        if (cmd.ExecuteNonQuery() < 0)
                //            throw new ProviderException("Unable to update failure count and window start.");
                //    }
                //    else
                //    {
                //        if (failureCount++ >= MaxInvalidPasswordAttempts)
                //        {
                //            // Password attempts have exceeded the failure threshold. Lock out
                //            // the user.

                //            cmd.CommandText = "UPDATE Users " +
                //                              "  SET IsLockedOut = ?, LastLockedOutDate = ? " +
                //                              "  WHERE Username = ? AND ApplicationName = ?";

                //            cmd.Parameters.Clear();

                //            cmd.Parameters.Add("@IsLockedOut", OdbcType.Bit).Value = true;
                //            cmd.Parameters.Add("@LastLockedOutDate", OdbcType.DateTime).Value = DateTime.Now;
                //            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //            if (cmd.ExecuteNonQuery() < 0)
                //                throw new ProviderException("Unable to lock out user.");
                //        }
                //        else
                //        {
                //            // Password attempts have not exceeded the failure threshold. Update
                //            // the failure counts. Leave the window the same.

                //            if (failureType == "password")
                //                cmd.CommandText = "UPDATE Users " +
                //                                  "  SET FailedPasswordAttemptCount = ?" +
                //                                  "  WHERE Username = ? AND ApplicationName = ?";

                //            if (failureType == "passwordAnswer")
                //                cmd.CommandText = "UPDATE Users " +
                //                                  "  SET FailedPasswordAnswerAttemptCount = ?" +
                //                                  "  WHERE Username = ? AND ApplicationName = ?";

                //            cmd.Parameters.Clear();

                //            cmd.Parameters.Add("@Count", OdbcType.Int).Value = failureCount;
                //            cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
                //            cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //            if (cmd.ExecuteNonQuery() < 0)
                //                throw new ProviderException("Unable to update failure count.");
                //        }
                //    }
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "UpdateFailureCount");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }
                //    conn.Close();
                //}
            }


            //
            // CheckPassword
            //   Compares password values based on the MembershipPasswordFormat.
            //

            private bool CheckPassword(string password, string dbpassword)
            {
                string pass1 = password;
                string pass2 = dbpassword;

                switch (PasswordFormat)
                {
                    case MembershipPasswordFormat.Encrypted:
                        pass2 = UnEncodePassword(dbpassword);
                        break;
                    case MembershipPasswordFormat.Hashed:
                        pass1 = EncodePassword(password);
                        break;
                    default:
                        break;
                }

                if (pass1 == pass2)
                {
                    return true;
                }

                return false;
            }


            //
            // EncodePassword
            //   Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
            //

            private string EncodePassword(string password)
            {
                string encodedPassword = password;

                switch (PasswordFormat)
                {
                    case MembershipPasswordFormat.Clear:
                        break;
                    case MembershipPasswordFormat.Encrypted:
                        encodedPassword =
                          Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
                        break;
                    case MembershipPasswordFormat.Hashed:
                        HMACSHA1 hash = new HMACSHA1();
                        hash.Key = HexToByte(machineKey.ValidationKey);
                        encodedPassword =
                          Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
                        break;
                    default:
                        throw new ProviderException("Unsupported password format.");
                }

                return encodedPassword;
            }


            //
            // UnEncodePassword
            //   Decrypts or leaves the password clear based on the PasswordFormat.
            //

            private string UnEncodePassword(string encodedPassword)
            {
                string password = encodedPassword;

                switch (PasswordFormat)
                {
                    case MembershipPasswordFormat.Clear:
                        break;
                    case MembershipPasswordFormat.Encrypted:
                        password =
                          Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
                        break;
                    case MembershipPasswordFormat.Hashed:
                        throw new ProviderException("Cannot unencode a hashed password.");
                    default:
                        throw new ProviderException("Unsupported password format.");
                }

                return password;
            }

            //
            // HexToByte
            //   Converts a hexadecimal string to a byte array. Used to convert encryption
            // key values from the configuration.
            //

            private byte[] HexToByte(string hexString)
            {
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }


            //
            // MembershipProvider.FindUsersByName
            //

            public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotSupportedException("this function is not enabled.");

                //SqlConnection conn = new SqlConnection(connectionString);
                //SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM users " +
                //          "WHERE Username LIKE ? AND ApplicationName = ?", conn);
                //cmd.Parameters.Add("@UsernameSearch", OdbcType.VarChar, 255).Value = usernameToMatch;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

                //MembershipUserCollection users = new MembershipUserCollection();

                //OdbcDataReader reader = null;

                //try
                //{
                //    conn.Open();
                //    totalRecords = (int)cmd.ExecuteScalar();

                //    if (totalRecords <= 0) { return users; }

                //    cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," +
                //      " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                //      " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " +
                //      " FROM Users " +
                //      " WHERE Username LIKE ? AND ApplicationName = ? " +
                //      " ORDER BY Username Asc";

                //    reader = cmd.ExecuteReader();

                //    int counter = 0;
                //    int startIndex = pageSize * pageIndex;
                //    int endIndex = startIndex + pageSize - 1;

                //    while (reader.Read())
                //    {
                //        if (counter >= startIndex)
                //        {
                //            MembershipUser u = GetUserFromReader(reader);
                //            users.Add(u);
                //        }

                //        if (counter >= endIndex) { cmd.Cancel(); }

                //        counter++;
                //    }
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "FindUsersByName");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }

                //    conn.Close();
                //}

                //return users;
            }

            //
            // MembershipProvider.FindUsersByEmail
            //

            public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotSupportedException("this function is not enabled.");
                //OdbcConnection conn = new OdbcConnection(connectionString);
                //OdbcCommand cmd = new OdbcCommand("SELECT Count(*) FROM Users " +
                //                                  "WHERE Email LIKE ? AND ApplicationName = ?", conn);
                //cmd.Parameters.Add("@EmailSearch", OdbcType.VarChar, 255).Value = emailToMatch;
                //cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = ApplicationName;

                //MembershipUserCollection users = new MembershipUserCollection();

                //OdbcDataReader reader = null;
                //totalRecords = 0;

                //try
                //{
                //    conn.Open();
                //    totalRecords = (int)cmd.ExecuteScalar();

                //    if (totalRecords <= 0) { return users; }

                //    cmd.CommandText = "SELECT PKID, Username, Email, PasswordQuestion," +
                //             " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
                //             " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate " +
                //             " FROM Users " +
                //             " WHERE Email LIKE ? AND ApplicationName = ? " +
                //             " ORDER BY Username Asc";

                //    reader = cmd.ExecuteReader();

                //    int counter = 0;
                //    int startIndex = pageSize * pageIndex;
                //    int endIndex = startIndex + pageSize - 1;

                //    while (reader.Read())
                //    {
                //        if (counter >= startIndex)
                //        {
                //            MembershipUser u = GetUserFromReader(reader);
                //            users.Add(u);
                //        }

                //        if (counter >= endIndex) { cmd.Cancel(); }

                //        counter++;
                //    }
                //}
                //catch (OdbcException e)
                //{
                //    if (WriteExceptionsToEventLog)
                //    {
                //        WriteToEventLog(e, "FindUsersByEmail");

                //        throw new ProviderException(exceptionMessage);
                //    }
                //    else
                //    {
                //        throw e;
                //    }
                //}
                //finally
                //{
                //    if (reader != null) { reader.Close(); }

                //    conn.Close();
                //}

                //return users;
            }


            //
            // WriteToEventLog
            //   A helper function that writes exception detail to the event log. Exceptions
            // are written to the event log as a security measure to avoid private database
            // details from being returned to the browser. If a method does not return a status
            // or boolean indicating the action succeeded or failed, a generic exception is also 
            // thrown by the caller.
            //

            private void WriteToEventLog(Exception e, string action)
            {
                EventLog log = new EventLog();
                log.Source = eventSource;
                log.Log = eventLog;

                string message = "An exception occurred communicating with the data source.\n\n";
                message += "Action: " + action + "\n\n";
                message += "Exception: " + e.ToString();

                log.WriteEntry(message);
            }

        }
    

}